package com.dz.risk.common.utils;

/**
 * 线程任务工具类
 *
 * @author doke
 * @date 2020/11/23 20:51
 */
public class ThreadTaskCalculateUtil {

    private ThreadTaskCalculateUtil() {
    }

    /**
     * IO密集型
     */
    public static final int IO_CONCENTRATED = 1;

    /**
     * CPU密集型
     */
    public static final int CPU_CONCENTRATED = 2;

    /**
     * 获取各线程任务处理量
     *
     * @param taskType            任务类型固定为: {@link ThreadTaskCalculateUtil#IO_CONCENTRATED} 和{@link ThreadTaskCalculateUtil#CPU_CONCENTRATED}
     * @param taskNum             任务总数
     * @param singleThreadTaskNum 预期各线程任务处理数
     * @return 各线程实际任务处理数
     */
    public static int geTeachThreadTaskLength(int taskType, int taskNum, int singleThreadTaskNum) {
        final int two = 2;

        //CPU核心数
        int cpuCoreNum = Runtime.getRuntime().availableProcessors();

        int threadNum = cpuCoreNum;

        if (IO_CONCENTRATED == taskType) {
            threadNum = cpuCoreNum * two;
        }

        if (taskNum >= threadNum * singleThreadTaskNum) {
            singleThreadTaskNum = taskNum / threadNum;
        }
        return singleThreadTaskNum;
    }
}
